package com.blank.web.filter;

import com.blank.web.bean.UserBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

/**
 * 编程实现过滤器的自定义,实现部分页面的过滤
 *
 */
@WebFilter(filterName = "LoginFilter",urlPatterns = {"/mainPage.jsp"})
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
       //1、实现对用户访问主页面的过滤操作，也就是用户登录后才能访问主界面，否则一律拦截
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
       //2、判断session是否有用户名中的信息，若有，则放行，没有，则去Cookie中寻找再做判断
       //2.1若session中有用户信息则直接放行
        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");

        //获取Servlet的请求路径
        String servletPath = httpServletRequest.getServletPath();
        String userName = null;
        if(null != user && servletPath.contains("loginServlet")){
           chain.doFilter(req,resp);
        }else{
            //2.2若还没有登录,则查询cookie信息中是否已经存放账户信息
            Cookie[] cookies = httpServletRequest.getCookies();
            System.out.println("数组中:"+ Arrays.toString(cookies));
            if(cookies != null && cookies.length > 0){
                for(Cookie cookie : cookies){
                    String name = cookie.getName();
                    if("userName".equals(name)){
                        userName = name;
                        System.out.println(userName);
                        break;
                    }
                }
            }
        }
        if(null != userName){
            chain.doFilter(req,resp);
        }else{
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
